package com.beverage.lemonade.UI;

import com.beverage.lemonade.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class SlideListFragment extends ListFragment {
	protected ListAdapter adapter;
	protected Context context;
	protected Activity activity;

	public SlideListFragment(Context context) {
		super();
		this.context = context;
		this.adapter = new ListAdapter(context);
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.list, null);
	}

	public void addOneItem(Intent intent, String Tag, int iconRes) {
		adapter.add(new Item(intent, Tag, iconRes));
	}

	public void addOneItem(Intent intent, String Tag) {
		adapter.add(new Item(intent, Tag));
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		activity = getActivity();
		setListAdapter(adapter);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		System.out.println(position);
		Item item = adapter.getItem(position);
		activity.finish();
		activity.overridePendingTransition(0, 0);
		context.startActivity(item.getIntent());
	}

	private class Item {
		public String tag;
		public int iconRes = 0;
		public Intent intent;

		public Item(Intent intent, String tag, int iconRes) {
			this.tag = tag;
			this.iconRes = iconRes;
			this.intent = intent;
		}

		public Item(Intent intent, String tag) {
			this.tag = tag;
			this.intent = intent;
		}

		public Intent getIntent() {
			return intent;
		}
	}

	public class ListAdapter extends ArrayAdapter<Item> {

		public ListAdapter(Context context) {
			super(context, 0);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(
						R.layout.row, null);
			}

			if (getItem(position).iconRes != 0) {
				ImageView icon = (ImageView) convertView
						.findViewById(R.id.row_icon);
				icon.setImageResource(getItem(position).iconRes);
			}

			TextView title = (TextView) convertView
					.findViewById(R.id.row_title);
			title.setText(getItem(position).tag);

			return convertView;
		}
	}

}
